﻿using System;
using System.Collections.Generic;
using System.Linq;
using E4RPTools;

namespace DBTractores
{
    public class PartUpdater : IProgressWorker
    {
        #region Members

        private readonly Result _errors;
        private readonly DataClassesDataContext _dataContext;
        private readonly List<Part> _existingParts;

        #endregion
        
        #region Events

        public event EventHandler DocumentProcessing;

        #endregion

        #region Properties

        public int DocumentCount { get; private set; }

        public int DocumentIndex { get; private set; }

        public string DocumentNumber { get; private set; }

        #endregion

        #region Public Methods

        public PartUpdater(Result errors, DataClassesDataContext dataContext, List<Part> existingParts)
        {
            _errors = errors;
            _dataContext = dataContext;
            _existingParts = existingParts;
        }

        public bool Work()
        {
            _errors.Reset();            
            DocumentCount = _existingParts.Count;
            return UpdateParts();            
        }        

        #endregion

        #region Protected Methods

        virtual protected void OnDocumentProcessing()
        {
            var documentProcessing = DocumentProcessing;
            if (documentProcessing != null)
                documentProcessing(this, new EventArgs());
        }

        #endregion

        #region Private Methods

        private bool UpdateParts()
        {       
            foreach (var product in _existingParts)
            {
                if (product.Selected)
                {
                    var price = from a in _dataContext.ArtigoMoedas where a.Artigo == product.Code select a;
                    price.First().PVP1 = product.Price;
                    _dataContext.SubmitChanges();
                }
                DocumentIndex++;
                OnDocumentProcessing();
            }
            return true;
        }

        #endregion
    }
}
